package com.powergisol.gis.point;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.powergisol.gis.util.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
            Throwable cause = authException.getCause();
            Result r = new Result();
            if(cause instanceof InvalidTokenException) {
                r.failure(401,"无效的token");
            }else{
                r.failure(401,"访问此资源需要身份验证");
            }
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), r);
            } catch (Exception e) {
                throw new ServletException();
            }
        }
}

